package srg

import (
	"encoding/json"
	"fmt"
	"time"

	"github.com/redis/go-redis/v9"
)

func MsgAdd(msgType string, msgTargetId string, msgInfo string, tiggerTime int64) int64 {
	//添加非队列消息
	return addMsg(&SrgMsg{
		MsgType:     msgType,
		MsgTargetId: msgTargetId,
		MsgInfo:     msgInfo,
		TiggerTime:  tiggerTime,
	})
}

// 5秒内的消息 直接处理
// 超过5秒的消息 延迟处理
func addMsg(msg *SrgMsg) int64 {

	if msg.QueueName == "" { //非队列消息
		msg.Id = GetFutureUniqueId(msg.TiggerTime / 1000)
	}

	msgBytes, _ := json.Marshal(msg)

	if msg.TiggerTime == 0 || msg.TiggerTime <= time.Now().UnixMilli() { //立即执行

		err := srds.Set(ctx, fmt.Sprintf("%s%s:%d", srgHead, oriMsgHead, msg.Id), string(msgBytes), 0).Err()
		if err != nil {
			panic(err)
		}

		srds.Publish(ctx, defMsgQueue, msg.Id)
		return msg.Id
	} else if msg.TiggerTime <= time.Now().UnixMilli()+7000 { //7秒内的消息 直接处理

		srds.Set(ctx, fmt.Sprintf("%s%s:%d", srgHead, oriMsgHead, msg.Id), string(msgBytes), 0)

		go func(sleepTime int64) {
			time.Sleep(time.Duration(sleepTime) * time.Millisecond)
			srds.Publish(ctx, defMsgQueue, msg.Id)
		}(msg.TiggerTime - time.Now().UnixMilli())

	} else { //延迟消息

		srds.ZAdd(ctx, delayMsgList, redis.Z{
			Score:  float64(msg.Id),
			Member: string(msgBytes),
		})

	}

	return msg.Id
}

// 监听系统
func listenMsg() {

	pubsub := srds.Subscribe(ctx, defMsgQueue)
	defer pubsub.Close()
	ch := pubsub.Channel()
	for msg := range ch {

		go dealMsg(msg.Payload)
	}

}
